
/**
 * 设置cookie
 * s20是代表20秒
 * h是指小时，如12小时则是：h12
 * d是天数，30天则：d30
 * @param name
 * @param value
 * @param time
 */
export function setCookie(name,value,time){
    var strsec = getsec(time);
    var exp = new Date();
    exp.setTime(exp.getTime() + strsec*1);
    document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();
}
function getsec(str){
    var str1=str.substring(1,str.length)*1;
    var str2=str.substring(0,1);
    if (str2=="s")	{
        return str1*1000;
    }
    else if (str2=="h")	{
        return str1*60*60*1000;
    }
    else if (str2=="d")	{
        return str1*24*60*60*1000;
    }
}

/**
 * 根据名称删除cookie
 * @param name
 */
export function delCookie(name) {
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    var cval = getCookie(name);
    if (cval != null) {
        document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
    }
}

/**
 * 获取cookie
 * @param name
 * @returns {string|null}
 */
export function getCookie(name){
    var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
    if(arr=document.cookie.match(reg)) return unescape(arr[2]);
    else return null;
}

/**
 * 清除所有
 */
export function clearCookie(){
    var keys=document.cookie.match(/[^ =;]+(?=\=)/g);
    if (keys) {
        for (var i = keys.length; i--;) ;
        document.cookie=keys[i]+'=0;expires=' + new Date( 0).toUTCString() ;
    }
}

/**
 * 获取所有cookie
 * @returns {[]}
 */
export function getCookieList(){
   return  list('connectData',null);
}

export function getBtnCookieList(value) {
   return  list('btn',value);
}

function list(str,value) {
    let obj = [];
    var strCookie = document.cookie;
    var arrCookie = strCookie.split("; ");
    for(var i = 0; i < arrCookie.length; i++){
        var arr = arrCookie[i].split("=");
        if (arr[0].indexOf(str) !== -1 && arr[0].indexOf(value==null?str:value) !== -1){
            let bean = JSON.parse(decodeURIComponent(arr[1]));
            obj.push(bean);
        }
    }
    return obj;
}

/**
 * 根据id 返回对象
 * @param id
 * @returns {any}
 */
export function getCookieObj(id){
    return JSON.parse(getCookie(id));
}

export function getNowTime() {
    return time(0);
}

function delNowTime(){
    return time(1)
}

function time(year){
    let dateTime
    let yy = new Date().getFullYear() - year
    let mm = new Date().getMonth() + 1
    let dd = new Date().getDate()
    let hh = new Date().getHours()
    let mf = new Date().getMinutes() < 10 ? '0' + new Date().getMinutes()
        :
        new Date().getMinutes()
    let ss = new Date().getSeconds() < 10 ? '0' + new Date().getSeconds()
        :
        new Date().getSeconds()
    dateTime = yy + '-' + mm + '-' + dd + ' ' + hh + ':' + mf + ':' + ss
    return dateTime
}